import org.apache.log4j.Logger

/**
 * User: wohlgemuth
 * Date: Jan 26, 2010
 * Time: 8:28:19 PM
 */
class FileHelper {
  private static def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

  /**
   * marks the given file as imported and for this reason ignored
   */
  public static void markFileAsImported(File file, Logger logger) {
    if (config.renameImportedFiles) {
      String dir = file.getParent()
      String name = file.getName()

      def reader = file.newReader()
      def destination = new File(dir, name + ".imported")

      logger.debug("copy file from ${file} to ${destination}")

      destination.withWriter {writer ->
        writer << reader
      }
      reader.close()

      logger.debug("delete ${file} -> ${file.delete()}")


    }
    else {
      logger.debug "renaming and deleting is disabled"
    }
  }

  /**
   * is this file accessible
   */
  public static def fileAccessible(File file) {
    if (file != null) {
      if (file.isFile()) {
        if (file.exists()) {
          return true
        }
      }
    }

    return false
  }

  /**
   * works on the given directory and executes the closure
   */
  public static def workOnDir(String dir, Closure closure, Logger logger, String extension) {
    logger.info "using dir: ${dir}"

    File dirFile = new File(dir)
    logger.info ("dir exist: ${dirFile.exists()}")

    dirFile.listFiles().each {File file ->

      def value = fileAccessible(file)

      if (value) {
        if (file.getName().endsWith(extension)) {
          logger.info "reading file: ${file}"

          try {
            closure(file)

            markFileAsImported(file, logger)
          }
          catch (Exception e) {
            logger.error "ignoring current file, cause an exception occured (${e.getMessage()}", e
          }
        }
        else{
          logger.debug "our extension doesn't support this file: ${file}"
        }

      }
    }

    logger.info("done with directory")

  }
}
